package top.cardone.log.func

import com.mongodb.DBObject
import org.springframework.data.mongodb.core.MongoTemplate
import top.cardone.context.ApplicationContextHolder
import top.cardone.context.util.StringUtils
import top.cardone.core.util.func.Func1

class InsertListFunc implements Func1<Object, List<Map<String, Object>>> {
    @Override
    Object func(List<Map<String, Object>> objects) {
        def mongoTemplate = ApplicationContextHolder.getBean(MongoTemplate.class)

        if (mongoTemplate == null) {
            new Integer[0]
        }

        Map<String, List<DBObject>> dbObjectsMap = [:]

        for (Map<String, Object> object : objects) {
            def collectionName = StringUtils.defaultIfBlank(object.collectionName, object.objectTypeCode)

            if (!collectionName) {
                continue
            }

            object.remove("collectionName")
            object.remove("objectTypeCode")

            List<DBObject> dbObjects = dbObjectsMap.get(collectionName)

            if (dbObjects == null) {
                dbObjects = [object]

                dbObjectsMap.put(collectionName, dbObjects)
            } else {
                dbObjects.add(object)
            }

            if (dbObjects.size() >= 50) {
                mongoTemplate.insert(dbObjects, collectionName)

                dbObjects.clear()
            }
        }

        for (Map.Entry<String, List<DBObject>> dbObjectsMapEntry : dbObjectsMap.entrySet()) {
            if (dbObjectsMapEntry.value.size() > 0) {
                mongoTemplate.insert(dbObjectsMapEntry.value, dbObjectsMapEntry.key)

                dbObjectsMapEntry.value.clear()
            }
        }

        new Integer[0]
    }
}